#!/bin/bash

# 数据库备份脚本
set -e

echo "💾 开始数据库备份..."

# 设置变量
BACKUP_DIR="./backups"
DATE=$(date +%Y%m%d_%H%M%S)
BACKUP_FILE="kason_world_${DATE}.sql"

# 创建备份目录
mkdir -p $BACKUP_DIR

# 从环境变量或配置文件读取数据库信息
DB_HOST=${MYSQL_HOST:-"139.159.190.115"}
DB_PORT=${MYSQL_PORT:-"3308"}
DB_USER=${MYSQL_USER:-"root"}
DB_PASS=${MYSQL_PASSWORD:-"Xx@123456"}
DB_NAME=${MYSQL_DATABASE:-"kason-world"}

echo "📊 备份数据库: $DB_NAME"
echo "🌐 数据库地址: $DB_HOST:$DB_PORT"

# 执行备份
if mysqldump -h"$DB_HOST" -P"$DB_PORT" -u"$DB_USER" -p"$DB_PASS" \
    --single-transaction \
    --routines \
    --triggers \
    --events \
    --add-drop-database \
    --add-drop-table \
    "$DB_NAME" > "$BACKUP_DIR/$BACKUP_FILE"; then
    
    echo "✅ 备份成功: $BACKUP_FILE"
    
    # 压缩备份文件
    gzip "$BACKUP_DIR/$BACKUP_FILE"
    echo "🗜️ 压缩完成: $BACKUP_FILE.gz"
    
    # 删除7天前的备份文件
    find $BACKUP_DIR -name "*.sql.gz" -mtime +7 -delete
    echo "🧹 清理7天前的备份文件"
    
    # 显示备份文件信息
    ls -lh "$BACKUP_DIR/$BACKUP_FILE.gz"
    
else
    echo "❌ 备份失败"
    exit 1
fi

echo "🎉 数据库备份完成！"
